package com.ny.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * MongoDB数据初始化器
 * 在应用启动时初始化MongoDB中的设备和设备状态数据
 */
@Component
public class MongoDataInitializer implements CommandLineRunner {

    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;

    @Override
    public void run(String... args) throws Exception {
        try (MongoClient mongoClient = MongoClients.create(mongoUri)) {
            MongoDatabase database = mongoClient.getDatabase("home_devices");

            // 获取集合
            MongoCollection<Document> devicesCollection = database.getCollection("devices");
            MongoCollection<Document> deviceStatusCollection = database.getCollection("device_status");

            // 清除现有数据
            DeleteResult devicesDeleted = devicesCollection.deleteMany(new Document());
            DeleteResult deviceStatusDeleted = deviceStatusCollection.deleteMany(new Document());

            System.out.println("已删除设备数据: " + devicesDeleted.getDeletedCount() + " 条");
            System.out.println("已删除设备状态数据: " + deviceStatusDeleted.getDeletedCount() + " 条");

            // 创建设备数据
            List<Document> devices = Arrays.asList(
                new Document()
                    .append("device_id", 1)
                    .append("device_sn", "SN1001")
                    .append("device_name", "客厅烟雾传感器")
                    .append("device_type", 5)
                    .append("room_id", 1)
                    .append("status", 1)
                    .append("protocol", "ZigBee")
                    .append("created_time", Date.from(LocalDateTime.of(2025, 9, 18, 14, 53, 26).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("device_id", 2)
                    .append("device_sn", "SN1002")
                    .append("device_name", "主卧吸顶灯")
                    .append("device_type", 1)
                    .append("room_id", 2)
                    .append("status", 1)
                    .append("protocol", "WiFi")
                    .append("created_time", Date.from(LocalDateTime.of(2025, 9, 18, 14, 53, 26).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("device_id", 3)
                    .append("device_sn", "SN1003")
                    .append("device_name", "客厅空调")
                    .append("device_type", 2)
                    .append("room_id", 1)
                    .append("status", 1)
                    .append("protocol", "WiFi")
                    .append("created_time", Date.from(LocalDateTime.of(2025, 9, 18, 14, 53, 26).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("device_id", 4)
                    .append("device_sn", "SN1004")
                    .append("device_name", "厨房燃气传感器")
                    .append("device_type", 5)
                    .append("room_id", 3)
                    .append("status", 1)
                    .append("protocol", "ZigBee")
                    .append("created_time", Date.from(LocalDateTime.of(2025, 9, 18, 14, 53, 26).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("device_id", 5)
                    .append("device_sn", "SN1005")
                    .append("device_name", "次卧窗帘电机")
                    .append("device_type", 4)
                    .append("room_id", 4)
                    .append("status", 0)
                    .append("protocol", "ZigBee")
                    .append("created_time", Date.from(LocalDateTime.of(2025, 9, 18, 14, 53, 26).toInstant(ZoneOffset.UTC)))
            );

            // 插入设备数据
            devicesCollection.insertMany(devices);
            System.out.println("已插入设备数据: " + devices.size() + " 条");

            // 创建设备状态数据
            List<Document> deviceStatuses = Arrays.asList(
                new Document()
                    .append("status_id", 1)
                    .append("device_id", 1)
                    .append("status_data", new Document()
                        .append("alarm", 0)
                        .append("battery", 95)
                        .append("smoke_level", 0))
                    .append("update_time", Date.from(LocalDateTime.of(2023, 10, 1, 8, 0, 0).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("status_id", 2)
                    .append("device_id", 2)
                    .append("status_data", new Document()
                        .append("color", "white")
                        .append("switch", 1)
                        .append("brightness", 80))
                    .append("update_time", Date.from(LocalDateTime.of(2023, 10, 1, 8, 30, 0).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("status_id", 3)
                    .append("device_id", 3)
                    .append("status_data", new Document()
                        .append("mode", "cool")
                        .append("temp", 26)
                        .append("switch", 1)
                        .append("fan_speed", 2))
                    .append("update_time", Date.from(LocalDateTime.of(2023, 10, 1, 9, 0, 0).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("status_id", 4)
                    .append("device_id", 4)
                    .append("status_data", new Document()
                        .append("alarm", 0)
                        .append("battery", 90)
                        .append("gas_level", 0))
                    .append("update_time", Date.from(LocalDateTime.of(2023, 10, 1, 9, 30, 0).toInstant(ZoneOffset.UTC))),

                new Document()
                    .append("status_id", 5)
                    .append("device_id", 5)
                    .append("status_data", new Document()
                        .append("switch", 0)
                        .append("battery", 85)
                        .append("position", 0))
                    .append("update_time", Date.from(LocalDateTime.of(2023, 10, 1, 10, 0, 0).toInstant(ZoneOffset.UTC)))
            );

            // 插入设备状态数据
            deviceStatusCollection.insertMany(deviceStatuses);
            System.out.println("已插入设备状态数据: " + deviceStatuses.size() + " 条");

            // 创建索引
            devicesCollection.createIndex(new Document("device_sn", 1), new IndexOptions().unique(true));
            devicesCollection.createIndex(new Document("room_id", 1));
            devicesCollection.createIndex(new Document("device_type", 1));
            deviceStatusCollection.createIndex(new Document("device_id", 1).append("update_time", -1));

            System.out.println("MongoDB索引创建完成");
            System.out.println("MongoDB初始化完成！");
        } catch (Exception e) {
            System.err.println("MongoDB初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}